package com.zhiche.lisa.lspm.service.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.zhiche.lisa.core.utils.HttpClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Objects;

@Component
public class TokenUtil {

    @Value("${security.oauth2.client.access-token-uri}")
    private String getTokenUrl;

    @Value("${security.oauth2.client.clientId}")
    private String getClinetId;

    @Value("${security.oauth2.client.clientSecret}")
    private String getClientSecret;

    @Value("${lisa.socketTimeout}")
    private Integer socketTimeout;

    /**
     * 根据refreshToken获取新的token
     * @param refreshToken
     * @return
     */
    public Map<String,String>  getRefreshToken(String refreshToken){
        Map<String,String> tokenMap = Maps.newHashMap();

        Map<String, String> parmers = Maps.newHashMap();
        parmers.put("client_id",getClinetId);
        parmers.put("client_secret",getClientSecret);
        parmers.put("grant_type","refresh_token");
        parmers.put("refresh_token",refreshToken);

        String strReturn1 = HttpClientUtil.post(getTokenUrl,parmers,10000);
        if(StringUtils.isNotEmpty(strReturn1)){
            JSONObject jsonObject2 = JSON.parseObject(strReturn1);
            if(Objects.nonNull(jsonObject2)){
                String  access_token = jsonObject2.getString("access_token");
                String authorization = "Bearer " + access_token;
                String refresh_token = jsonObject2.getString("refresh_token");
                tokenMap.put("token",authorization);
                tokenMap.put("refresh_token",refresh_token);
            }
        }

        return tokenMap;
    }


    public String getTenantToken(String techAccountIdentifier) {
        Map<String, String> parmers = Maps.newHashMap();
        parmers.put("username", techAccountIdentifier);
        parmers.put("password", "123456");
        parmers.put("client_id", getClinetId);
        parmers.put("client_secret", getClientSecret);
        parmers.put("grant_type", "password");
        String result = HttpClientUtil.post(getTokenUrl, parmers, socketTimeout);
        if (StringUtils.isEmpty(result)) return null;
        JSONObject jsonObject2 = JSON.parseObject(result);
        if (Objects.nonNull(jsonObject2)) {
            String access_token = jsonObject2.getString("access_token");
            String authorization = "Bearer " + access_token;
            return authorization;
        } else {
            return null;
        }
    }
}
